import json

from django.contrib.auth import authenticate
from django.http import HttpResponse
from django.shortcuts import render
from django.views.decorators.csrf import ensure_csrf_cookie
from rest_framework.views import APIView
from rest_framework import generics
from rest_framework.response import Response

from .models import MyUser
from .pagination import MyPageNumberPagination
from .response import R
from django.contrib.auth import authenticate, login, logout
from .serializers import *
from rest_framework import filters
from django.middleware.csrf import get_token


# Create your views here.
@ensure_csrf_cookie
def get_csrftoken(request):
    token = get_token(request)
    return HttpResponse(json.dumps({'token': token}), content_type="application/json,charset=utf-8",
                        headers={'Access-Control-Allow-Origin': '*', 'X-CSRFToken': token})


class is_login(APIView):
    def get(self, request):
        if request.user.is_authenticated:
            return R.ok(data={
                'id': request.user.id,
                'username': request.user.username,
                'is_superuser': request.user.is_superuser
            })
        else:
            return R.failed(msg='未登录')


class LoginView(APIView):
    def post(self, request):
        username = request.data.get('username')
        password = request.data.get('password')
        user = authenticate(request, username=username, password=password)
        if user is not None:
            login(request, user)
            return R.ok(msg="登录成功", data=UserSerializer(user).data)
        else:
            return R.failed(msg="登录失败")


class Logout(APIView):
    def get(self, request):
        try:
            logout(request)
            return R.ok(msg="退出成功")
        except Exception as e:
            return R.failed(msg=e.__str__())


class UserDetail(APIView):
    def get(self, request, pk, format=None):
        user = MyUser.objects.get(id=pk)
        return R.ok(UserSerializer(user).data)


class CreateSuper(APIView):
    def post(self, request):
        try:
            data = {**request.data}
            data.pop('confirm_pw')
            MyUser.objects.create_user(**data)
            return R.ok(msg='创建成功')
        except Exception as e:
            return R.failed(msg=e.__str__())


class UserList(generics.ListAPIView):
    queryset = MyUser.objects.all()
    serializer_class = UserSerializer
    pagination_class = MyPageNumberPagination
    # filter_backends = (filters.SearchFilter,)
    filterset_fields = ["belong_to_group", "gender", "nationality", "age", "join_group_age"]
    search_fields = ('username',)

    def get(self, request, *args, **kwargs):
        res = super().get(request, *args, **kwargs)
        return R.ok(data=res.data)


class GroupDetail(APIView):
    def get(self, request):
        try:
            full_name = request.query_params.get('full_name')
            obj = MyGroup.objects.get(full_name=full_name)
            return R.ok(GroupSerializer(obj).data)
        except Exception as e:
            return R.failed(msg=e.__str__())

    def post(self, request):
        try:
            MyGroup.objects.create(**request.data)
            return R.ok(msg="创建成功")
        except Exception as e:
            print(e)
            return R.failed(msg="创建失败")

    def put(self, request):
        try:
            MyGroup.objects.filter(id=request.data.get("id")).update(**request.data)
            return R.ok(msg="修改成功")
        except Exception as e:
            print(e)
            return R.failed(msg=e.__str__())


class GroupList(generics.ListAPIView):
    queryset = MyGroup.objects.all()
    serializer_class = GroupSerializer
    pagination_class = MyPageNumberPagination
    search_fields = ('full_name', 'brief_name')

    def get(self, request, *args, **kwargs):
        res = super().get(request, *args, **kwargs)
        return R.ok(data=res.data)


class GroupMember(APIView):
    def get(self, request):
        full_name = request.query_params.get("full_name")
        objs = MyUser.objects.filter(belong_to_group=full_name)
        print(objs)
        if objs:
            return R.ok(data=UserSerializer(objs, many=True).data)
        else:
            return R.failed(msg="该组织没有成员")


class AddMember(APIView):
    def post(self, request):
        if not request.data.get("password"):
            request.data['password'] = "123456"
        try:
            MyUser.objects.create_user(**request.data)
            return R.ok(msg="创建成功")
        except Exception as e:
            print(e)
            return R.failed(msg=e.__str__())


class DeleteMember(APIView):
    def delete(self, request, pk):
        try:
            obj = MyUser.objects.get(id=pk)
            obj.delete()
            return R.ok(msg="删除成功")
        except Exception as e:
            return R.failed(msg=e.__str__())


class UpdateMember(APIView):
    def put(self, request):
        try:
            MyUser.objects.filter(id=request.data.get("id")).update(**request.data)
            return R.ok(msg="修改成功")
        except Exception as e:
            print(e)
            return R.failed(msg=e.__str__())


class CreateNews(APIView):
    # authentication_classes = []
    def post(self, request):
        try:
            title = request.data.get("title")
            content = request.data.get("content")
            user = request.user
            print(user)
            News.objects.create(title=title, content=content, author=user.username, full_name=user.belong_to_group)
            return R.ok(msg="创建成功")
        except Exception as e:
            return R.failed(msg=e.__str__())


class NewsList(generics.ListAPIView):
    queryset = News.objects.all()
    serializer_class = NewsListSerializer
    search_fields = ('title', 'content',)
    filterset_fields = ["author"]

    def get(self, request, *args, **kwargs):
        res = super(NewsList, self).get(request, *args, **kwargs)
        return R.ok(data=res.data)


class NewsDetail(APIView):
    def get(self, request, pk):
        try:
            obj = News.objects.get(id=pk)
            if obj:
                return R.ok(NewDetailSerializer(obj).data)
        except Exception as e:
            return R.failed(msg=e.__str__())
